let sysop delete trackbacks
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 /**#@-*/
40
41 /**
42 * Constructor and clear the article
43 * @param mixed &$title
44 */
45 function Article( &$title ) {
46 $this->mTitle =& $title;
47 $this->clear();
48 }
49
50 /**
51 * get the title object of the article
52 * @public
53 */
54 function getTitle() {
55 return $this->mTitle;
56 }
57
58 /**
59 * Clear the object
60 * @private
61 */
62 function clear() {
63 $this->mDataLoaded = false;
64 $this->mContentLoaded = false;
65
66 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
67 $this->mRedirectedFrom = $this->mUserText =
68 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
69 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
70 $this->mTouched = '19700101000000';
71 $this->mForUpdate = false;
72 $this->mIsRedirect = false;
73 $this->mRevIdFetched = 0;
74 }
75
76 /**
77 * Note that getContent/loadContent may follow redirects if
78 * not told otherwise, and so may cause a change to mTitle.
79 *
80 * @param $noredir
81 * @return Return the text of this revision
82 */
83 function getContent( $noredir ) {
84 global $wgRequest, $wgUser, $wgOut;
85
86 # Get variables from query string :P
87 $action = $wgRequest->getText( 'action', 'view' );
88 $section = $wgRequest->getText( 'section' );
89 $preload = $wgRequest->getText( 'preload' );
90
91 $fname = 'Article::getContent';
92 wfProfileIn( $fname );
93
94 if ( 0 == $this->getID() ) {
95 if ( 'edit' == $action ) {
96 wfProfileOut( $fname );
97
98 # If requested, preload some text.
99 $text=$this->getPreloadedText($preload);
100
101 # We used to put MediaWiki:Newarticletext here if
102 # $text was empty at this point.
103 # This is now shown above the edit box instead.
104 return $text;
105 }
106 wfProfileOut( $fname );
107 $wgOut->setRobotpolicy( 'noindex,nofollow' );
108 return wfMsg( 'noarticletext' );
109 } else {
110 $this->loadContent( $noredir );
111 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
112 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
113 $wgUser->isIP($this->mTitle->getText()) &&
114 $action=='view'
115 ) {
116 wfProfileOut( $fname );
117 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
118 } else {
119 if($action=='edit') {
120 if($section!='') {
121 if($section=='new') {
122 wfProfileOut( $fname );
123 $text=$this->getPreloadedText($preload);
124 return $text;
125 }
126
127 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
128 # comments to be stripped as well)
129 $rv=$this->getSection($this->mContent,$section);
130 wfProfileOut( $fname );
131 return $rv;
132 }
133 }
134 wfProfileOut( $fname );
135 return $this->mContent;
136 }
137 }
138 }
139
140 /**
141 This function accepts a title string as parameter
142 ($preload). If this string is non-empty, it attempts
143 to fetch the current revision text.
144 */
145 function getPreloadedText($preload) {
146 if($preload) {
147 $preloadTitle=Title::newFromText($preload);
148 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
149 $rev=Revision::newFromTitle($preloadTitle);
150 if($rev) {
151 return $rev->getText();
152 }
153 }
154 }
155 return '';
156 }
157
158 /**
159 * This function returns the text of a section, specified by a number ($section).
160 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
161 * the first section before any such heading (section 0).
162 *
163 * If a section contains subsections, these are also returned.
164 *
165 * @param string $text text to look in
166 * @param integer $section section number
167 * @return string text of the requested section
168 */
169 function getSection($text,$section) {
170
171 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
172 # comments to be stripped as well)
173 $striparray=array();
174 $parser=new Parser();
175 $parser->mOutputType=OT_WIKI;
176 $striptext=$parser->strip($text, $striparray, true);
177
178 # now that we can be sure that no pseudo-sections are in the source,
179 # split it up by section
180 $secs =
181 preg_split(
182 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
183 $striptext, -1,
184 PREG_SPLIT_DELIM_CAPTURE);
185 if($section==0) {
186 $rv=$secs[0];
187 } else {
188 $headline=$secs[$section*2-1];
189 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
190 $hlevel=$matches[1];
191
192 # translate wiki heading into level
193 if(strpos($hlevel,'=')!==false) {
194 $hlevel=strlen($hlevel);
195 }
196
197 $rv=$headline. $secs[$section*2];
198 $count=$section+1;
199
200 $break=false;
201 while(!empty($secs[$count*2-1]) && !$break) {
202
203 $subheadline=$secs[$count*2-1];
204 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
205 $subhlevel=$matches[1];
206 if(strpos($subhlevel,'=')!==false) {
207 $subhlevel=strlen($subhlevel);
208 }
209 if($subhlevel > $hlevel) {
210 $rv.=$subheadline.$secs[$count*2];
211 }
212 if($subhlevel <= $hlevel) {
213 $break=true;
214 }
215 $count++;
216
217 }
218 }
219 # reinsert stripped tags
220 $rv=$parser->unstrip($rv,$striparray);
221 $rv=$parser->unstripNoWiki($rv,$striparray);
222 $rv=trim($rv);
223 return $rv;
224
225 }
226
227 /**
228 * Return an array of the columns of the "cur"-table
229 */
230 function getContentFields() {
231 return $wgArticleContentFields = array(
232 'old_text','old_flags',
233 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
234 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
235 }
236
237 /**
238 * Return the oldid of the article that is to be shown.
239 * For requests with a "direction", this is not the oldid of the
240 * query
241 */
242 function getOldID() {
243 global $wgRequest, $wgOut;
244 static $lastid;
245
246 if ( isset( $lastid ) ) {
247 return $lastid;
248 }
249 # Query variables :P
250 $oldid = $wgRequest->getVal( 'oldid' );
251 if ( isset( $oldid ) ) {
252 $oldid = IntVal( $oldid );
253 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
254 $nextid = $this->mTitle->getNextRevisionID( $oldid );
255 if ( $nextid ) {
256 $oldid = $nextid;
257 } else {
258 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
259 }
260 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
261 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
262 if ( $previd ) {
263 $oldid = $previd;
264 } else {
265 # TODO
266 }
267 }
268 $lastid = $oldid;
269 }
270 return @$oldid; # "@" to be able to return "unset" without PHP complaining
271 }
272
273
274 /**
275 * Load the revision (including cur_text) into this object
276 */
277 function loadContent( $noredir = false ) {
278 global $wgOut, $wgRequest;
279
280 if ( $this->mContentLoaded ) return;
281
282 # Query variables :P
283 $oldid = $this->getOldID();
284 $redirect = $wgRequest->getVal( 'redirect' );
285
286 $fname = 'Article::loadContent';
287
288 # Pre-fill content with error message so that if something
289 # fails we'll have something telling us what we intended.
290
291 $t = $this->mTitle->getPrefixedText();
292
293 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
294 || $wgRequest->getCheck( 'rdfrom' );
295 $this->mOldId = $oldid;
296 $this->fetchContent( $oldid, $noredir, true );
297 }
298
299
300 /**
301 * Fetch a page record with the given conditions
302 * @param Database $dbr
303 * @param array $conditions
304 * @access private
305 */
306 function pageData( &$dbr, $conditions ) {
307 return $dbr->selectRow( 'page',
308 array(
309 'page_id',
310 'page_namespace',
311 'page_title',
312 'page_restrictions',
313 'page_counter',
314 'page_is_redirect',
315 'page_is_new',
316 'page_random',
317 'page_touched',
318 'page_latest',
319 'page_len' ),
320 $conditions,
321 'Article::pageData' );
322 }
323
324 function pageDataFromTitle( &$dbr, $title ) {
325 return $this->pageData( $dbr, array(
326 'page_namespace' => $title->getNamespace(),
327 'page_title' => $title->getDBkey() ) );
328 }
329
330 function pageDataFromId( &$dbr, $id ) {
331 return $this->pageData( $dbr, array(
332 'page_id' => IntVal( $id ) ) );
333 }
334
335 /**
336 * Set the general counter, title etc data loaded from
337 * some source.
338 *
339 * @param object $data
340 * @access private
341 */
342 function loadPageData( $data ) {
343 $this->mTitle->loadRestrictions( $data->page_restrictions );
344 $this->mTitle->mRestrictionsLoaded = true;
345
346 $this->mCounter = $data->page_counter;
347 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
348 $this->mIsRedirect = $data->page_is_redirect;
349 $this->mLatest = $data->page_latest;
350
351 $this->mDataLoaded = true;
352 }
353
354 /**
355 * Get text of an article from database
356 * @param int $oldid 0 for whatever the latest revision is
357 * @param bool $noredir Set to false to follow redirects
358 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
359 * @return string
360 */
361 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
362 if ( $this->mContentLoaded ) {
363 return $this->mContent;
364 }
365 $dbr =& $this->getDB();
366 $fname = 'Article::fetchContent';
367
368 # Pre-fill content with error message so that if something
369 # fails we'll have something telling us what we intended.
370 $t = $this->mTitle->getPrefixedText();
371 if( $oldid ) {
372 $t .= ',oldid='.$oldid;
373 }
374 if( isset( $redirect ) ) {
375 $redirect = ($redirect == 'no') ? 'no' : 'yes';
376 $t .= ',redirect='.$redirect;
377 }
378 $this->mContent = wfMsg( 'missingarticle', $t );
379
380 if( $oldid ) {
381 $revision = Revision::newFromId( $oldid );
382 if( is_null( $revision ) ) {
383 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
384 return false;
385 }
386 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
387 if( !$data ) {
388 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
389 return false;
390 }
391 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
392 $this->loadPageData( $data );
393 } else {
394 if( !$this->mDataLoaded ) {
395 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
396 if( !$data ) {
397 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
398 return false;
399 }
400 $this->loadPageData( $data );
401 }
402 $revision = Revision::newFromId( $this->mLatest );
403 if( is_null( $revision ) ) {
404 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
405 return false;
406 }
407 }
408
409 # If we got a redirect, follow it (unless we've been told
410 # not to by either the function parameter or the query
411 if ( !$oldid && !$noredir ) {
412 $rt = Title::newFromRedirect( $revision->getText() );
413 # process if title object is valid and not special:userlogout
414 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
415 # Gotta hand redirects to special pages differently:
416 # Fill the HTTP response "Location" header and ignore
417 # the rest of the page we're on.
418 global $wgDisableHardRedirects;
419 if( $globalTitle && !$wgDisableHardRedirects ) {
420 global $wgOut;
421 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
422 $source = $this->mTitle->getFullURL( 'redirect=no' );
423 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
424 return false;
425 }
426 if ( $rt->getNamespace() == NS_SPECIAL ) {
427 $wgOut->redirect( $rt->getFullURL() );
428 return false;
429 }
430 }
431 $redirData = $this->pageDataFromTitle( $dbr, $rt );
432 if( $redirData ) {
433 $redirRev = Revision::newFromId( $redirData->page_latest );
434 if( !is_null( $redirRev ) ) {
435 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
436 $this->mTitle = $rt;
437 $data = $redirData;
438 $this->loadPageData( $data );
439 $revision = $redirRev;
440 }
441 }
442 }
443 }
444
445 # if the title's different from expected, update...
446 if( $globalTitle ) {
447 global $wgTitle;
448 if( !$this->mTitle->equals( $wgTitle ) ) {
449 $wgTitle = $this->mTitle;
450 }
451 }
452
453 # Back to the business at hand...
454 $this->mContent = $revision->getText();
455
456 $this->mUser = $revision->getUser();
457 $this->mUserText = $revision->getUserText();
458 $this->mComment = $revision->getComment();
459 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
460
461 $this->mRevIdFetched = $revision->getID();
462 $this->mContentLoaded = true;
463 $this->mRevision =& $revision;
464
465 return $this->mContent;
466 }
467
468 /**
469 * Gets the article text without using so many damn globals
470 * Returns false on error
471 *
472 * @param integer $oldid
473 */
474 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
475 return $this->fetchContent( $oldid, $noredir, false );
476 }
477
478 /**
479 * Read/write accessor to select FOR UPDATE
480 */
481 function forUpdate( $x = NULL ) {
482 return wfSetVar( $this->mForUpdate, $x );
483 }
484
485 /**
486 * Get the database which should be used for reads
487 */
488 function &getDB() {
489 #if ( $this->mForUpdate ) {
490 $ret =& wfGetDB( DB_MASTER );
491 #} else {
492 # $ret =& wfGetDB( DB_SLAVE );
493 #}
494 return $ret;
495 }
496
497 /**
498 * Get options for all SELECT statements
499 * Can pass an option array, to which the class-wide options will be appended
500 */
501 function getSelectOptions( $options = '' ) {
502 if ( $this->mForUpdate ) {
503 if ( is_array( $options ) ) {
504 $options[] = 'FOR UPDATE';
505 } else {
506 $options = 'FOR UPDATE';
507 }
508 }
509 return $options;
510 }
511
512 /**
513 * Return the Article ID
514 */
515 function getID() {
516 if( $this->mTitle ) {
517 return $this->mTitle->getArticleID();
518 } else {
519 return 0;
520 }
521 }
522
523 /**
524 * Returns true if this article exists in the database.
525 * @return bool
526 */
527 function exists() {
528 return $this->getId() != 0;
529 }
530
531 /**
532 * Get the view count for this article
533 */
534 function getCount() {
535 if ( -1 == $this->mCounter ) {
536 $id = $this->getID();
537 $dbr =& $this->getDB();
538 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
539 'Article::getCount', $this->getSelectOptions() );
540 }
541 return $this->mCounter;
542 }
543
544 /**
545 * Would the given text make this article a "good" article (i.e.,
546 * suitable for including in the article count)?
547 * @param string $text Text to analyze
548 * @return integer 1 if it can be counted else 0
549 */
550 function isCountable( $text ) {
551 global $wgUseCommaCount;
552
553 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
554 if ( $this->isRedirect( $text ) ) { return 0; }
555 $token = ($wgUseCommaCount ? ',' : '[[' );
556 if ( false === strstr( $text, $token ) ) { return 0; }
557 return 1;
558 }
559
560 /**
561 * Tests if the article text represents a redirect
562 */
563 function isRedirect( $text = false ) {
564 if ( $text === false ) {
565 $this->loadContent();
566 $titleObj = Title::newFromRedirect( $this->fetchContent() );
567 } else {
568 $titleObj = Title::newFromRedirect( $text );
569 }
570 return $titleObj !== NULL;
571 }
572
573 /**
574 * Returns true if the currently-referenced revision is the current edit
575 * to this page (and it exists).
576 * @return bool
577 */
578 function isCurrent() {
579 return $this->exists() &&
580 isset( $this->mRevision ) &&
581 $this->mRevision->isCurrent();
582 }
583
584 /**
585 * Loads everything except the text
586 * This isn't necessary for all uses, so it's only done if needed.
587 * @private
588 */
589 function loadLastEdit() {
590 global $wgOut;
591
592 if ( -1 != $this->mUser )
593 return;
594
595 # New or non-existent articles have no user information
596 $id = $this->getID();
597 if ( 0 == $id ) return;
598
599 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
600 if( !is_null( $this->mLastRevision ) ) {
601 $this->mUser = $this->mLastRevision->getUser();
602 $this->mUserText = $this->mLastRevision->getUserText();
603 $this->mTimestamp = $this->mLastRevision->getTimestamp();
604 $this->mComment = $this->mLastRevision->getComment();
605 $this->mMinorEdit = $this->mLastRevision->isMinor();
606 }
607 }
608
609 function getTimestamp() {
610 $this->loadLastEdit();
611 return $this->mTimestamp;
612 }
613
614 function getUser() {
615 $this->loadLastEdit();
616 return $this->mUser;
617 }
618
619 function getUserText() {
620 $this->loadLastEdit();
621 return $this->mUserText;
622 }
623
624 function getComment() {
625 $this->loadLastEdit();
626 return $this->mComment;
627 }
628
629 function getMinorEdit() {
630 $this->loadLastEdit();
631 return $this->mMinorEdit;
632 }
633
634 function getRevIdFetched() {
635 $this->loadLastEdit();
636 return $this->mRevIdFetched;
637 }
638
639 function getContributors($limit = 0, $offset = 0) {
640 $fname = 'Article::getContributors';
641
642 # XXX: this is expensive; cache this info somewhere.
643
644 $title = $this->mTitle;
645 $contribs = array();
646 $dbr =& $this->getDB();
647 $revTable = $dbr->tableName( 'revision' );
648 $userTable = $dbr->tableName( 'user' );
649 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
650 $ns = $title->getNamespace();
651 $user = $this->getUser();
652 $pageId = $this->getId();
653
654 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
655 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
656 WHERE rev_page = $pageId
657 AND rev_user != $user
658 GROUP BY rev_user, rev_user_text, user_real_name
659 ORDER BY timestamp DESC";
660
661 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
662 $sql .= ' '. $this->getSelectOptions();
663
664 $res = $dbr->query($sql, $fname);
665
666 while ( $line = $dbr->fetchObject( $res ) ) {
667 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
668 }
669
670 $dbr->freeResult($res);
671 return $contribs;
672 }
673
674 /**
675 * This is the default action of the script: just view the page of
676 * the given title.
677 */
678 function view() {
679 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
680 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
681 global $wgEnotif, $wgParser, $wgParserCache, $wgUseTrackbacks;
682 $sk = $wgUser->getSkin();
683
684 $fname = 'Article::view';
685 wfProfileIn( $fname );
686 # Get variables from query string
687 $oldid = $this->getOldID();
688 $diff = $wgRequest->getVal( 'diff' );
689 $rcid = $wgRequest->getVal( 'rcid' );
690 $rdfrom = $wgRequest->getVal( 'rdfrom' );
691
692 $wgOut->setArticleFlag( true );
693 $wgOut->setRobotpolicy( 'index,follow' );
694 # If we got diff and oldid in the query, we want to see a
695 # diff page instead of the article.
696
697 if ( !is_null( $diff ) ) {
698 require_once( 'DifferenceEngine.php' );
699 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
700
701 $de = new DifferenceEngine( $oldid, $diff, $rcid );
702 // DifferenceEngine directly fetched the revision:
703 $this->mRevIdFetched = $de->mNewid;
704 $de->showDiffPage();
705
706 if( $diff == 0 ) {
707 # Run view updates for current revision only
708 $this->viewUpdates();
709 }
710 wfProfileOut( $fname );
711 return;
712 }
713
714 if ( empty( $oldid ) && $this->checkTouched() ) {
715 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
716
717 if( $wgOut->checkLastModified( $this->mTouched ) ){
718 wfProfileOut( $fname );
719 return;
720 } else if ( $this->tryFileCache() ) {
721 # tell wgOut that output is taken care of
722 $wgOut->disable();
723 $this->viewUpdates();
724 wfProfileOut( $fname );
725 return;
726 }
727 }
728 # Should the parser cache be used?
729 $pcache = $wgEnableParserCache &&
730 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
731 $this->exists() &&
732 empty( $oldid );
733 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
734
735 $outputDone = false;
736 if ( $pcache ) {
737 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
738 $outputDone = true;
739 }
740 }
741 if ( !$outputDone ) {
742 $text = $this->getContent( false ); # May change mTitle by following a redirect
743
744 # Another whitelist check in case oldid or redirects are altering the title
745 if ( !$this->mTitle->userCanRead() ) {
746 $wgOut->loginToUse();
747 $wgOut->output();
748 exit;
749 }
750
751 # We're looking at an old revision
752
753 if ( !empty( $oldid ) ) {
754 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
755 $wgOut->setRobotpolicy( 'noindex,follow' );
756 }
757 if ( '' != $this->mRedirectedFrom ) {
758 $sk = $wgUser->getSkin();
759 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
760 'redirect=no' );
761 $s = wfMsg( 'redirectedfrom', $redir );
762 $wgOut->setSubtitle( $s );
763
764 # Can't cache redirects
765 $pcache = false;
766 } elseif ( !empty( $rdfrom ) ) {
767 global $wgRedirectSources;
768 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
769 $sk = $wgUser->getSkin();
770 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
771 $s = wfMsg( 'redirectedfrom', $redir );
772 $wgOut->setSubtitle( $s );
773 }
774 }
775
776 # wrap user css and user js in pre and don't parse
777 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
778 if (
779 $this->mTitle->getNamespace() == NS_USER &&
780 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
781 ) {
782 $wgOut->addWikiText( wfMsg('clearyourcache'));
783 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
784 } else if ( $rt = Title::newFromRedirect( $text ) ) {
785 # Display redirect
786 $imageUrl = $wgStylePath.'/common/images/redirect.png';
787 $targetUrl = $rt->escapeLocalURL();
788 $titleText = htmlspecialchars( $rt->getPrefixedText() );
789 $link = $sk->makeLinkObj( $rt );
790
791 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
792 '<span class="redirectText">'.$link.'</span>' );
793
794 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
795 $catlinks = $parseout->getCategoryLinks();
796 $wgOut->addCategoryLinks($catlinks);
797 $skin = $wgUser->getSkin();
798 } else if ( $pcache ) {
799 # Display content and save to parser cache
800 $wgOut->addPrimaryWikiText( $text, $this );
801 } else {
802 # Display content, don't attempt to save to parser cache
803
804 # Don't show section-edit links on old revisions... this way lies madness.
805 if( !$this->isCurrent() ) {
806 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
807 }
808 $wgOut->addWikiText( $text );
809
810 if( !$this->isCurrent() ) {
811 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
812 }
813 }
814 }
815 /* title may have been set from the cache */
816 $t = $wgOut->getPageTitle();
817 if( empty( $t ) ) {
818 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
819 }
820
821 # If we have been passed an &rcid= parameter, we want to give the user a
822 # chance to mark this new article as patrolled.
823 if ( $wgUseRCPatrol
824 && !is_null($rcid)
825 && $rcid != 0
826 && $wgUser->isLoggedIn()
827 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
828 {
829 $wgOut->addHTML(
830 "<div class='patrollink'>" .
831 wfMsg ( 'markaspatrolledlink',
832 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
833 ) .
834 '</div>'
835 );
836 }
837
838 # Trackbacks
839 if ($wgUseTrackbacks)
840 $this->addTrackbacks();
841
842 # Put link titles into the link cache
843 $wgOut->transformBuffer();
844
845 # Add link titles as META keywords
846 $wgOut->addMetaTags() ;
847
848 $this->viewUpdates();
849 wfProfileOut( $fname );
850 }
851
852 function addTrackbacks() {
853 global $wgOut, $wgUser;
854
855 $dbr = wfGetDB(DB_SLAVE);
856 $tbs = $dbr->select(
857 /* FROM */ 'trackbacks',
858 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
859 /* WHERE */ array('tb_page' => $this->getID())
860 );
861
862 if (!$dbr->numrows($tbs))
863 return;
864
865 $tbtext = "";
866 while ($o = $dbr->fetchObject($tbs)) {
867 $rmvtext = "";
868 if ($wgUser->isSysop()) {
869 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
870 . $o->tb_id . "&token=" . $wgUser->editToken());
871 $rmvtxt = wfMsg('trackbackremove', $delurl);
872 }
873 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
874 $o->tb_title,
875 $o->tb_url,
876 $o->tb_ex,
877 $o->tb_name,
878 $rmvtxt);
879 }
880 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
881 }
882
883 function deletetrackback() {
884 global $wgUser, $wgRequest, $wgOut, $wgTitle;
885
886 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
887 $wgOut->addWikitext(wfMsg('sessionfailure'));
888 return;
889 }
890
891 if ((!$wgUser->isAllowed('delete'))) {
892 $wgOut->sysopRequired();
893 return;
894 }
895
896 if (wfReadOnly()) {
897 $wgOut->readOnlyPage();
898 return;
899 }
900
901 $db = wfGetDB(DB_MASTER);
902 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
903 $wgTitle->invalidateCache();
904 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
905 }
906
907 function render() {
908 global $wgOut;
909
910 $wgOut->setArticleBodyOnly(true);
911 $this->view();
912 }
913
914 /**
915 * Insert a new empty page record for this article.
916 * This *must* be followed up by creating a revision
917 * and running $this->updateToLatest( $rev_id );
918 * or else the record will be left in a funky state.
919 * Best if all done inside a transaction.
920 *
921 * @param Database $dbw
922 * @param string $restrictions
923 * @return int The newly created page_id key
924 * @access private
925 */
926 function insertOn( &$dbw, $restrictions = '' ) {
927 $fname = 'Article::insertOn';
928 wfProfileIn( $fname );
929
930 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
931 $dbw->insert( 'page', array(
932 'page_id' => $page_id,
933 'page_namespace' => $this->mTitle->getNamespace(),
934 'page_title' => $this->mTitle->getDBkey(),
935 'page_counter' => 0,
936 'page_restrictions' => $restrictions,
937 'page_is_redirect' => 0, # Will set this shortly...
938 'page_is_new' => 1,
939 'page_random' => wfRandom(),
940 'page_touched' => $dbw->timestamp(),
941 'page_latest' => 0, # Fill this in shortly...
942 ), $fname );
943 $newid = $dbw->insertId();
944
945 $this->mTitle->resetArticleId( $newid );
946
947 wfProfileOut( $fname );
948 return $newid;
949 }
950
951 /**
952 * Update the page record to point to a newly saved revision.
953 *
954 * @param Database $dbw
955 * @param Revision $revision -- for ID number, and text used to set
956 length and redirect status fields
957 * @param int $lastRevision -- if given, will not overwrite the page field
958 * when different from the currently set value.
959 * Giving 0 indicates the new page flag should
960 * be set on.
961 * @return bool true on success, false on failure
962 * @access private
963 */
964 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
965 $fname = 'Article::updateToRevision';
966 wfProfileIn( $fname );
967
968 $conditions = array( 'page_id' => $this->getId() );
969 if( !is_null( $lastRevision ) ) {
970 # An extra check against threads stepping on each other
971 $conditions['page_latest'] = $lastRevision;
972 }
973 $text = $revision->getText();
974 $dbw->update( 'page',
975 array( /* SET */
976 'page_latest' => $revision->getId(),
977 'page_touched' => $dbw->timestamp(),
978 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
979 'page_is_redirect' => Article::isRedirect( $text ),
980 'page_len' => strlen( $text ),
981 ),
982 $conditions,
983 $fname );
984
985 wfProfileOut( $fname );
986 return ( $dbw->affectedRows() != 0 );
987 }
988
989 /**
990 * If the given revision is newer than the currently set page_latest,
991 * update the page record. Otherwise, do nothing.
992 *
993 * @param Database $dbw
994 * @param Revision $revision
995 */
996 function updateIfNewerOn( &$dbw, $revision ) {
997 $fname = 'Article::updateIfNewerOn';
998 wfProfileIn( $fname );
999
1000 $row = $dbw->selectRow(
1001 array( 'revision', 'page' ),
1002 array( 'rev_id', 'rev_timestamp' ),
1003 array(
1004 'page_id' => $this->getId(),
1005 'page_latest=rev_id' ),
1006 $fname );
1007 if( $row ) {
1008 if( $row->rev_timestamp >= $revision->getTimestamp() ) {
1009 wfProfileOut( $fname );
1010 return false;
1011 }
1012 $prev = $row->rev_id;
1013 } else {
1014 # No or missing previous revision; mark the page as new
1015 $prev = 0;
1016 }
1017
1018 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1019 wfProfileOut( $fname );
1020 return $ret;
1021 }
1022
1023 /**
1024 * Theoretically we could defer these whole insert and update
1025 * functions for after display, but that's taking a big leap
1026 * of faith, and we want to be able to report database
1027 * errors at some point.
1028 * @private
1029 */
1030 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1031 global $wgOut, $wgUser;
1032 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1033
1034 $fname = 'Article::insertNewArticle';
1035
1036 $this->mGoodAdjustment = $this->isCountable( $text );
1037 $this->mTotalAdjustment = 1;
1038
1039 $ns = $this->mTitle->getNamespace();
1040 $ttl = $this->mTitle->getDBkey();
1041
1042 # If this is a comment, add the summary as headline
1043 if($comment && $summary!="") {
1044 $text="== {$summary} ==\n\n".$text;
1045 }
1046 $text = $this->preSaveTransform( $text );
1047 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1048 $now = wfTimestampNow();
1049
1050 $dbw =& wfGetDB( DB_MASTER );
1051
1052 # Add the page record; stake our claim on this title!
1053 $newid = $this->insertOn( $dbw );
1054
1055 # Save the revision text...
1056 $revision = new Revision( array(
1057 'page' => $newid,
1058 'comment' => $summary,
1059 'minor_edit' => $isminor,
1060 'text' => $text
1061 ) );
1062 $revisionId = $revision->insertOn( $dbw );
1063
1064 $this->mTitle->resetArticleID( $newid );
1065
1066 # Update the page record with revision data
1067 $this->updateRevisionOn( $dbw, $revision, 0 );
1068
1069 Article::onArticleCreate( $this->mTitle );
1070 if(!$suppressRC) {
1071 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1072 '', strlen( $text ), $revisionId );
1073 }
1074
1075 if ($watchthis) {
1076 if(!$this->mTitle->userIsWatching()) $this->watch();
1077 } else {
1078 if ( $this->mTitle->userIsWatching() ) {
1079 $this->unwatch();
1080 }
1081 }
1082
1083 # The talk page isn't in the regular link tables, so we need to update manually:
1084 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1085 $dbw->update( 'page',
1086 array( 'page_touched' => $dbw->timestamp($now) ),
1087 array( 'page_namespace' => $talkns,
1088 'page_title' => $ttl ),
1089 $fname );
1090
1091 # standard deferred updates
1092 $this->editUpdates( $text, $summary, $isminor, $now );
1093
1094 $oldid = 0; # new article
1095 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1096 }
1097
1098 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1099 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
1100 if ($section != '') {
1101 if( is_null( $edittime ) ) {
1102 $rev = Revision::newFromTitle( $this->mTitle );
1103 } else {
1104 $dbw =& wfGetDB( DB_MASTER );
1105 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1106 }
1107 $oldtext = $rev->getText();
1108
1109 if($section=='new') {
1110 if($summary) $subject="== {$summary} ==\n\n";
1111 $text=$oldtext."\n\n".$subject.$text;
1112 } else {
1113
1114 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1115 # comments to be stripped as well)
1116 $striparray=array();
1117 $parser=new Parser();
1118 $parser->mOutputType=OT_WIKI;
1119 $oldtext=$parser->strip($oldtext, $striparray, true);
1120
1121 # now that we can be sure that no pseudo-sections are in the source,
1122 # split it up
1123 # Unfortunately we can't simply do a preg_replace because that might
1124 # replace the wrong section, so we have to use the section counter instead
1125 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1126 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1127 $secs[$section*2]=$text."\n\n"; // replace with edited
1128
1129 # section 0 is top (intro) section
1130 if($section!=0) {
1131
1132 # headline of old section - we need to go through this section
1133 # to determine if there are any subsections that now need to
1134 # be erased, as the mother section has been replaced with
1135 # the text of all subsections.
1136 $headline=$secs[$section*2-1];
1137 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1138 $hlevel=$matches[1];
1139
1140 # determine headline level for wikimarkup headings
1141 if(strpos($hlevel,'=')!==false) {
1142 $hlevel=strlen($hlevel);
1143 }
1144
1145 $secs[$section*2-1]=''; // erase old headline
1146 $count=$section+1;
1147 $break=false;
1148 while(!empty($secs[$count*2-1]) && !$break) {
1149
1150 $subheadline=$secs[$count*2-1];
1151 preg_match(
1152 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1153 $subhlevel=$matches[1];
1154 if(strpos($subhlevel,'=')!==false) {
1155 $subhlevel=strlen($subhlevel);
1156 }
1157 if($subhlevel > $hlevel) {
1158 // erase old subsections
1159 $secs[$count*2-1]='';
1160 $secs[$count*2]='';
1161 }
1162 if($subhlevel <= $hlevel) {
1163 $break=true;
1164 }
1165 $count++;
1166
1167 }
1168
1169 }
1170 $text=join('',$secs);
1171 # reinsert the stuff that we stripped out earlier
1172 $text=$parser->unstrip($text,$striparray);
1173 $text=$parser->unstripNoWiki($text,$striparray);
1174 }
1175
1176 }
1177 return $text;
1178 }
1179
1180 /**
1181 * Change an existing article. Puts the previous version back into the old table, updates RC
1182 * and all necessary caches, mostly via the deferred update array.
1183 *
1184 * It is possible to call this function from a command-line script, but note that you should
1185 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1186 */
1187 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1188 global $wgOut, $wgUser;
1189 global $wgDBtransactions, $wgMwRedir;
1190 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList, $wgUseFileCache;
1191
1192 $fname = 'Article::updateArticle';
1193 $good = true;
1194
1195 $isminor = ( $minor && $wgUser->isLoggedIn() );
1196 if ( $this->isRedirect( $text ) ) {
1197 # Remove all content but redirect
1198 # This could be done by reconstructing the redirect from a title given by
1199 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1200 # wants to see
1201 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1202 $redir = 1;
1203 $text = $m[1] . "\n";
1204 }
1205 }
1206 else { $redir = 0; }
1207
1208 $text = $this->preSaveTransform( $text );
1209 $dbw =& wfGetDB( DB_MASTER );
1210 $now = wfTimestampNow();
1211
1212 # Update article, but only if changed.
1213
1214 # It's important that we either rollback or complete, otherwise an attacker could
1215 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1216 # could conceivably have the same effect, especially if cur is locked for long periods.
1217 if( !$wgDBtransactions ) {
1218 $userAbort = ignore_user_abort( true );
1219 }
1220
1221 $oldtext = $this->getContent( true );
1222 $oldsize = strlen( $oldtext );
1223 $newsize = strlen( $text );
1224 $lastRevision = 0;
1225
1226 if ( 0 != strcmp( $text, $oldtext ) ) {
1227 $this->mGoodAdjustment = $this->isCountable( $text )
1228 - $this->isCountable( $oldtext );
1229 $this->mTotalAdjustment = 0;
1230 $now = wfTimestampNow();
1231
1232 $lastRevision = $dbw->selectField(
1233 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1234
1235 $revision = new Revision( array(
1236 'page' => $this->getId(),
1237 'comment' => $summary,
1238 'minor_edit' => $isminor,
1239 'text' => $text
1240 ) );
1241 $revisionId = $revision->insertOn( $dbw );
1242
1243 # Update page
1244 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1245
1246 if( !$ok ) {
1247 /* Belated edit conflict! Run away!! */
1248 $good = false;
1249 } else {
1250 # Update recentchanges and purge cache and whatnot
1251 $bot = (int)($wgUser->isBot() || $forceBot);
1252 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1253 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1254 $revisionId );
1255 Article::onArticleEdit( $this->mTitle );
1256 }
1257 }
1258
1259 if( !$wgDBtransactions ) {
1260 ignore_user_abort( $userAbort );
1261 }
1262
1263 if ( $good ) {
1264 if ($watchthis) {
1265 if (!$this->mTitle->userIsWatching()) $this->watch();
1266 } else {
1267 if ( $this->mTitle->userIsWatching() ) {
1268 $this->unwatch();
1269 }
1270 }
1271 # standard deferred updates
1272 $this->editUpdates( $text, $summary, $minor, $now );
1273
1274
1275 $urls = array();
1276 # Template namespace
1277 # Purge all articles linking here
1278 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1279 $titles = $this->mTitle->getLinksTo();
1280 Title::touchArray( $titles );
1281 if ( $wgUseSquid ) {
1282 foreach ( $titles as $title ) {
1283 $urls[] = $title->getInternalURL();
1284 }
1285 }
1286 }
1287
1288 # Squid updates
1289 if ( $wgUseSquid ) {
1290 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1291 $u = new SquidUpdate( $urls );
1292 array_push( $wgPostCommitUpdateList, $u );
1293 }
1294
1295 # File cache
1296 if ( $wgUseFileCache ) {
1297 $cm = new CacheManager($this->mTitle);
1298 @unlink($cm->fileCacheName());
1299 }
1300
1301 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1302 }
1303 return $good;
1304 }
1305
1306 /**
1307 * After we've either updated or inserted the article, update
1308 * the link tables and redirect to the new page.
1309 */
1310 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1311 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1312 global $wgUseEnotif;
1313
1314 $wgLinkCache = new LinkCache();
1315
1316 if ( !$wgUseDumbLinkUpdate ) {
1317 # Preload links to reduce lock time
1318 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1319 $wgLinkCache->preFill( $this->mTitle );
1320 $wgLinkCache->clear();
1321 }
1322 }
1323
1324 # Parse the text and replace links with placeholders
1325 $wgOut = new OutputPage();
1326
1327 # Pass the current title along in case we're creating a wiki page
1328 # which is different than the currently displayed one (e.g. image
1329 # pages created on file uploads); otherwise, link updates will
1330 # go wrong.
1331 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1332
1333 if ( !$wgUseDumbLinkUpdate ) {
1334 # Move the current links back to the second register
1335 $wgLinkCache->swapRegisters();
1336
1337 # Get old version of link table to allow incremental link updates
1338 # Lock this data now since it is needed for an update
1339 $wgLinkCache->forUpdate( true );
1340 $wgLinkCache->preFill( $this->mTitle );
1341
1342 # Swap this old version back into its rightful place
1343 $wgLinkCache->swapRegisters();
1344 }
1345
1346 if( $this->isRedirect( $text ) )
1347 $r = 'redirect=no';
1348 else
1349 $r = '';
1350 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1351
1352 if ( $wgUseEnotif ) {
1353 # this would be better as an extension hook
1354 include_once( "UserMailer.php" );
1355 $wgEnotif = new EmailNotification ();
1356 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1357 }
1358 }
1359
1360 /**
1361 * Mark this particular edit as patrolled
1362 */
1363 function markpatrolled() {
1364 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1365 $wgOut->setRobotpolicy( 'noindex,follow' );
1366
1367 if ( !$wgUseRCPatrol )
1368 {
1369 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1370 return;
1371 }
1372 if ( $wgUser->isAnon() )
1373 {
1374 $wgOut->loginToUse();
1375 return;
1376 }
1377 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1378 {
1379 $wgOut->sysopRequired();
1380 return;
1381 }
1382 $rcid = $wgRequest->getVal( 'rcid' );
1383 if ( !is_null ( $rcid ) )
1384 {
1385 RecentChange::markPatrolled( $rcid );
1386 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1387 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1388
1389 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1390 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1391 }
1392 else
1393 {
1394 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1395 }
1396 }
1397
1398 /**
1399 * Validate function
1400 */
1401 function validate() {
1402 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1403
1404 if ( !$wgUseValidation ) # Are we using article validation at all?
1405 {
1406 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1407 return ;
1408 }
1409
1410 $wgOut->setRobotpolicy( 'noindex,follow' );
1411 $revision = $wgRequest->getVal( 'revision' );
1412
1413 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1414
1415 $v = new Validation ;
1416 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1417 $t = $v->showList ( $this ) ;
1418 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1419 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1420 else
1421 $t = $v->validatePageForm ( $this , $revision ) ;
1422
1423 $wgOut->addHTML ( $t ) ;
1424 }
1425
1426 /**
1427 * Add this page to $wgUser's watchlist
1428 */
1429
1430 function watch() {
1431
1432 global $wgUser, $wgOut;
1433
1434 if ( $wgUser->isAnon() ) {
1435 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1436 return;
1437 }
1438 if ( wfReadOnly() ) {
1439 $wgOut->readOnlyPage();
1440 return;
1441 }
1442
1443 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1444
1445 $wgUser->addWatch( $this->mTitle );
1446 $wgUser->saveSettings();
1447
1448 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1449
1450 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1451 $wgOut->setRobotpolicy( 'noindex,follow' );
1452
1453 $link = $this->mTitle->getPrefixedText();
1454 $text = wfMsg( 'addedwatchtext', $link );
1455 $wgOut->addWikiText( $text );
1456 }
1457
1458 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1459 }
1460
1461 /**
1462 * Stop watching a page
1463 */
1464
1465 function unwatch() {
1466
1467 global $wgUser, $wgOut;
1468
1469 if ( $wgUser->isAnon() ) {
1470 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1471 return;
1472 }
1473 if ( wfReadOnly() ) {
1474 $wgOut->readOnlyPage();
1475 return;
1476 }
1477
1478 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1479
1480 $wgUser->removeWatch( $this->mTitle );
1481 $wgUser->saveSettings();
1482
1483 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1484
1485 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1486 $wgOut->setRobotpolicy( 'noindex,follow' );
1487
1488 $link = $this->mTitle->getPrefixedText();
1489 $text = wfMsg( 'removedwatchtext', $link );
1490 $wgOut->addWikiText( $text );
1491 }
1492
1493 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1494 }
1495
1496 /**
1497 * protect a page
1498 */
1499 function protect( $limit = 'sysop' ) {
1500 global $wgUser, $wgOut, $wgRequest;
1501
1502 if ( ! $wgUser->isAllowed('protect') ) {
1503 $wgOut->sysopRequired();
1504 return;
1505 }
1506 if ( wfReadOnly() ) {
1507 $wgOut->readOnlyPage();
1508 return;
1509 }
1510 $id = $this->mTitle->getArticleID();
1511 if ( 0 == $id ) {
1512 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1513 return;
1514 }
1515
1516 $confirm = $wgRequest->wasPosted() &&
1517 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1518 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1519 $reason = $wgRequest->getText( 'wpReasonProtect' );
1520
1521 if ( $confirm ) {
1522 $dbw =& wfGetDB( DB_MASTER );
1523 $dbw->update( 'page',
1524 array( /* SET */
1525 'page_touched' => $dbw->timestamp(),
1526 'page_restrictions' => (string)$limit
1527 ), array( /* WHERE */
1528 'page_id' => $id
1529 ), 'Article::protect'
1530 );
1531
1532 $restrictions = "move=" . $limit;
1533 if( !$moveonly ) {
1534 $restrictions .= ":edit=" . $limit;
1535 }
1536 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1537
1538 $dbw =& wfGetDB( DB_MASTER );
1539 $dbw->update( 'page',
1540 array( /* SET */
1541 'page_touched' => $dbw->timestamp(),
1542 'page_restrictions' => $restrictions
1543 ), array( /* WHERE */
1544 'page_id' => $id
1545 ), 'Article::protect'
1546 );
1547
1548 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1549
1550 $log = new LogPage( 'protect' );
1551 if ( $limit === '' ) {
1552 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1553 } else {
1554 $log->addEntry( 'protect', $this->mTitle, $reason );
1555 }
1556 $wgOut->redirect( $this->mTitle->getFullURL() );
1557 }
1558 return;
1559 } else {
1560 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1561 return $this->confirmProtect( '', $reason, $limit );
1562 }
1563 }
1564
1565 /**
1566 * Output protection confirmation dialog
1567 */
1568 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1569 global $wgOut, $wgUser;
1570
1571 wfDebug( "Article::confirmProtect\n" );
1572
1573 $sub = $this->mTitle->getPrefixedText();
1574 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1575
1576 $check = '';
1577 $protcom = '';
1578 $moveonly = '';
1579
1580 if ( $limit === '' ) {
1581 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1582 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1583 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1584 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1585 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1586 } else {
1587 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1588 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1589 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1590 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1591 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1592 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1593 }
1594
1595 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1596 $token = htmlspecialchars( $wgUser->editToken() );
1597
1598 $wgOut->addHTML( "
1599 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1600 <table border='0'>
1601 <tr>
1602 <td align='right'>
1603 <label for='wpReasonProtect'>{$protcom}:</label>
1604 </td>
1605 <td align='left'>
1606 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1607 </td>
1608 </tr>" );
1609 if($moveonly != '') {
1610 $wgOut->AddHTML( "
1611 <tr>
1612 <td align='right'>
1613 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1614 </td>
1615 <td align='left'>
1616 <label for='wpMoveOnly'>{$moveonly}</label>
1617 </td>
1618 </tr> " );
1619 }
1620 $wgOut->addHTML( "
1621 <tr>
1622 <td>&nbsp;</td>
1623 <td>
1624 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1625 </td>
1626 </tr>
1627 </table>
1628 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1629 </form>" );
1630
1631 $wgOut->returnToMain( false );
1632 }
1633
1634 /**
1635 * Unprotect the pages
1636 */
1637 function unprotect() {
1638 return $this->protect( '' );
1639 }
1640
1641 /*
1642 * UI entry point for page deletion
1643 */
1644 function delete() {
1645 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1646 $fname = 'Article::delete';
1647 $confirm = $wgRequest->wasPosted() &&
1648 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1649 $reason = $wgRequest->getText( 'wpReason' );
1650
1651 # This code desperately needs to be totally rewritten
1652
1653 # Check permissions
1654 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1655 $wgOut->sysopRequired();
1656 return;
1657 }
1658 if( wfReadOnly() ) {
1659 $wgOut->readOnlyPage();
1660 return;
1661 }
1662
1663 # Better double-check that it hasn't been deleted yet!
1664 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1665 if( !$this->mTitle->exists() ) {
1666 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1667 return;
1668 }
1669
1670 if( $confirm ) {
1671 $this->doDelete( $reason );
1672 return;
1673 }
1674
1675 # determine whether this page has earlier revisions
1676 # and insert a warning if it does
1677 # we select the text because it might be useful below
1678 $dbr =& $this->getDB();
1679 $ns = $this->mTitle->getNamespace();
1680 $title = $this->mTitle->getDBkey();
1681 $revisions = $dbr->select( array( 'page', 'revision' ),
1682 array( 'rev_id', 'rev_user_text' ),
1683 array(
1684 'page_namespace' => $ns,
1685 'page_title' => $title,
1686 'rev_page = page_id'
1687 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1688 );
1689
1690 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1691 $skin=$wgUser->getSkin();
1692 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1693 $wgOut->addHTML( $skin->historyLink() .'</b>');
1694 }
1695
1696 # Fetch cur_text
1697 $rev =& Revision::newFromTitle( $this->mTitle );
1698
1699 # Fetch name(s) of contributors
1700 $rev_name = '';
1701 $all_same_user = true;
1702 while( $row = $dbr->fetchObject( $revisions ) ) {
1703 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1704 $all_same_user = false;
1705 } else {
1706 $rev_name = $row->rev_user_text;
1707 }
1708 }
1709
1710 if( !is_null( $rev ) ) {
1711 # if this is a mini-text, we can paste part of it into the deletion reason
1712 $text = $rev->getText();
1713
1714 #if this is empty, an earlier revision may contain "useful" text
1715 $blanked = false;
1716 if( $text == '' ) {
1717 $prev = $rev->getPrevious();
1718 if( $prev ) {
1719 $text = $prev->getText();
1720 $blanked = true;
1721 }
1722 }
1723
1724 $length = strlen( $text );
1725
1726 # this should not happen, since it is not possible to store an empty, new
1727 # page. Let's insert a standard text in case it does, though
1728 if( $length == 0 && $reason === '' ) {
1729 $reason = wfMsg( 'exblank' );
1730 }
1731
1732 if( $length < 500 && $reason === '' ) {
1733 # comment field=255, let's grep the first 150 to have some user
1734 # space left
1735 global $wgContLang;
1736 $text = $wgContLang->truncate( $text, 150, '...' );
1737
1738 # let's strip out newlines
1739 $text = preg_replace( "/[\n\r]/", '', $text );
1740
1741 if( !$blanked ) {
1742 if( !$all_same_user ) {
1743 $reason = wfMsg( 'excontent', $text );
1744 } else {
1745 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1746 }
1747 } else {
1748 $reason = wfMsg( 'exbeforeblank', $text );
1749 }
1750 }
1751 }
1752
1753 return $this->confirmDelete( '', $reason );
1754 }
1755
1756 /**
1757 * Output deletion confirmation dialog
1758 */
1759 function confirmDelete( $par, $reason ) {
1760 global $wgOut, $wgUser;
1761
1762 wfDebug( "Article::confirmDelete\n" );
1763
1764 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1765 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1766 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1767 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1768
1769 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1770
1771 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1772 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1773 $token = htmlspecialchars( $wgUser->editToken() );
1774
1775 $wgOut->addHTML( "
1776 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1777 <table border='0'>
1778 <tr>
1779 <td align='right'>
1780 <label for='wpReason'>{$delcom}:</label>
1781 </td>
1782 <td align='left'>
1783 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1784 </td>
1785 </tr>
1786 <tr>
1787 <td>&nbsp;</td>
1788 <td>
1789 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1790 </td>
1791 </tr>
1792 </table>
1793 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1794 </form>\n" );
1795
1796 $wgOut->returnToMain( false );
1797 }
1798
1799
1800 /**
1801 * Perform a deletion and output success or failure messages
1802 */
1803 function doDelete( $reason ) {
1804 global $wgOut, $wgUser, $wgContLang;
1805 $fname = 'Article::doDelete';
1806 wfDebug( $fname."\n" );
1807
1808 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1809 if ( $this->doDeleteArticle( $reason ) ) {
1810 $deleted = $this->mTitle->getPrefixedText();
1811
1812 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1813 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1814
1815 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1816 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1817
1818 $wgOut->addWikiText( $text );
1819 $wgOut->returnToMain( false );
1820 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1821 } else {
1822 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1823 }
1824 }
1825 }
1826
1827 /**
1828 * Back-end article deletion
1829 * Deletes the article with database consistency, writes logs, purges caches
1830 * Returns success
1831 */
1832 function doDeleteArticle( $reason ) {
1833 global $wgUser;
1834 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1835 global $wgUseTrackbacks;
1836
1837 $fname = 'Article::doDeleteArticle';
1838 wfDebug( $fname."\n" );
1839
1840 $dbw =& wfGetDB( DB_MASTER );
1841 $ns = $this->mTitle->getNamespace();
1842 $t = $this->mTitle->getDBkey();
1843 $id = $this->mTitle->getArticleID();
1844
1845 if ( $t == '' || $id == 0 ) {
1846 return false;
1847 }
1848
1849 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1850 array_push( $wgDeferredUpdateList, $u );
1851
1852 $linksTo = $this->mTitle->getLinksTo();
1853
1854 # Squid purging
1855 if ( $wgUseSquid ) {
1856 $urls = array(
1857 $this->mTitle->getInternalURL(),
1858 $this->mTitle->getInternalURL( 'history' )
1859 );
1860
1861 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1862 array_push( $wgPostCommitUpdateList, $u );
1863
1864 }
1865
1866 # Client and file cache invalidation
1867 Title::touchArray( $linksTo );
1868
1869
1870 // For now, shunt the revision data into the archive table.
1871 // Text is *not* removed from the text table; bulk storage
1872 // is left intact to avoid breaking block-compression or
1873 // immutable storage schemes.
1874 //
1875 // For backwards compatibility, note that some older archive
1876 // table entries will have ar_text and ar_flags fields still.
1877 //
1878 // In the future, we may keep revisions and mark them with
1879 // the rev_deleted field, which is reserved for this purpose.
1880 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1881 array(
1882 'ar_namespace' => 'page_namespace',
1883 'ar_title' => 'page_title',
1884 'ar_comment' => 'rev_comment',
1885 'ar_user' => 'rev_user',
1886 'ar_user_text' => 'rev_user_text',
1887 'ar_timestamp' => 'rev_timestamp',
1888 'ar_minor_edit' => 'rev_minor_edit',
1889 'ar_rev_id' => 'rev_id',
1890 'ar_text_id' => 'rev_text_id',
1891 ), array(
1892 'page_id' => $id,
1893 'page_id = rev_page'
1894 ), $fname
1895 );
1896
1897 # Now that it's safely backed up, delete it
1898 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1899 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1900
1901 if ($wgUseTrackbacks)
1902 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1903
1904 # Clean up recentchanges entries...
1905 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1906
1907 # Finally, clean up the link tables
1908 $t = $this->mTitle->getPrefixedDBkey();
1909
1910 Article::onArticleDelete( $this->mTitle );
1911
1912 # Delete outgoing links
1913 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1914 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1915 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1916
1917 # Log the deletion
1918 $log = new LogPage( 'delete' );
1919 $log->addEntry( 'delete', $this->mTitle, $reason );
1920
1921 # Clear the cached article id so the interface doesn't act like we exist
1922 $this->mTitle->resetArticleID( 0 );
1923 $this->mTitle->mArticleID = 0;
1924 return true;
1925 }
1926
1927 /**
1928 * Revert a modification
1929 */
1930 function rollback() {
1931 global $wgUser, $wgOut, $wgRequest;
1932 $fname = 'Article::rollback';
1933
1934 if ( ! $wgUser->isAllowed('rollback') ) {
1935 $wgOut->sysopRequired();
1936 return;
1937 }
1938 if ( wfReadOnly() ) {
1939 $wgOut->readOnlyPage( $this->getContent( true ) );
1940 return;
1941 }
1942 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1943 array( $this->mTitle->getPrefixedText(),
1944 $wgRequest->getVal( 'from' ) ) ) ) {
1945 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1946 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1947 return;
1948 }
1949 $dbw =& wfGetDB( DB_MASTER );
1950
1951 # Enhanced rollback, marks edits rc_bot=1
1952 $bot = $wgRequest->getBool( 'bot' );
1953
1954 # Replace all this user's current edits with the next one down
1955 $tt = $this->mTitle->getDBKey();
1956 $n = $this->mTitle->getNamespace();
1957
1958 # Get the last editor, lock table exclusively
1959 $dbw->begin();
1960 $current = Revision::newFromTitle( $this->mTitle );
1961 if( is_null( $current ) ) {
1962 # Something wrong... no page?
1963 $dbw->rollback();
1964 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1965 return;
1966 }
1967
1968 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1969 if( $from != $current->getUserText() ) {
1970 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1971 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1972 htmlspecialchars( $this->mTitle->getPrefixedText()),
1973 htmlspecialchars( $from ),
1974 htmlspecialchars( $current->getUserText() ) ) );
1975 if( $current->getComment() != '') {
1976 $wgOut->addHTML(
1977 wfMsg( 'editcomment',
1978 htmlspecialchars( $current->getComment() ) ) );
1979 }
1980 return;
1981 }
1982
1983 # Get the last edit not by this guy
1984 $user = IntVal( $current->getUser() );
1985 $user_text = $dbw->addQuotes( $current->getUserText() );
1986 $s = $dbw->selectRow( 'revision',
1987 array( 'rev_id', 'rev_timestamp' ),
1988 array(
1989 'rev_page' => $current->getPage(),
1990 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1991 ), $fname,
1992 array(
1993 'USE INDEX' => 'page_timestamp',
1994 'ORDER BY' => 'rev_timestamp DESC' )
1995 );
1996 if( $s === false ) {
1997 # Something wrong
1998 $dbw->rollback();
1999 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2000 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2001 return;
2002 }
2003
2004 if ( $bot ) {
2005 # Mark all reverted edits as bot
2006 $dbw->update( 'recentchanges',
2007 array( /* SET */
2008 'rc_bot' => 1
2009 ), array( /* WHERE */
2010 'rc_cur_id' => $current->getPage(),
2011 'rc_user_text' => $current->getUserText(),
2012 "rc_timestamp > '{$s->rev_timestamp}'",
2013 ), $fname
2014 );
2015 }
2016
2017 # Save it!
2018 $target = Revision::newFromId( $s->rev_id );
2019 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
2020
2021 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2022 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2023 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
2024
2025 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
2026 Article::onArticleEdit( $this->mTitle );
2027
2028 $dbw->commit();
2029 $wgOut->returnToMain( false );
2030 }
2031
2032
2033 /**
2034 * Do standard deferred updates after page view
2035 * @private
2036 */
2037 function viewUpdates() {
2038 global $wgDeferredUpdateList, $wgUseEnotif;
2039
2040 if ( 0 != $this->getID() ) {
2041 global $wgDisableCounters;
2042 if( !$wgDisableCounters ) {
2043 Article::incViewCount( $this->getID() );
2044 $u = new SiteStatsUpdate( 1, 0, 0 );
2045 array_push( $wgDeferredUpdateList, $u );
2046 }
2047 }
2048
2049 # Update newtalk status if user is reading their own
2050 # talk page
2051
2052 global $wgUser;
2053 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
2054 $this->mTitle->getText() == $wgUser->getName())
2055 {
2056 if ( $wgUseEnotif ) {
2057 require_once( 'UserTalkUpdate.php' );
2058 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
2059 } else {
2060 $wgUser->setNewtalk(0);
2061 $wgUser->saveNewtalk();
2062 }
2063 } elseif ( $wgUseEnotif ) {
2064 $wgUser->clearNotification( $this->mTitle );
2065 }
2066
2067 }
2068
2069 /**
2070 * Do standard deferred updates after page edit.
2071 * Every 1000th edit, prune the recent changes table.
2072 * @private
2073 * @param string $text
2074 */
2075 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2076 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2077 global $wgMessageCache, $wgUser, $wgUseEnotif;
2078
2079 wfSeedRandom();
2080 if ( 0 == mt_rand( 0, 999 ) ) {
2081 # Periodically flush old entries from the recentchanges table.
2082 global $wgRCMaxAge;
2083 $dbw =& wfGetDB( DB_MASTER );
2084 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2085 $recentchanges = $dbw->tableName( 'recentchanges' );
2086 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2087 $dbw->query( $sql );
2088 }
2089 $id = $this->getID();
2090 $title = $this->mTitle->getPrefixedDBkey();
2091 $shortTitle = $this->mTitle->getDBkey();
2092
2093 if ( 0 != $id ) {
2094 $u = new LinksUpdate( $id, $title );
2095 array_push( $wgDeferredUpdateList, $u );
2096 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2097 array_push( $wgDeferredUpdateList, $u );
2098 $u = new SearchUpdate( $id, $title, $text );
2099 array_push( $wgDeferredUpdateList, $u );
2100
2101 # If this is another user's talk page, update newtalk
2102
2103 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2104 if ( $wgUseEnotif ) {
2105 require_once( 'UserTalkUpdate.php' );
2106 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2107 $minoredit, $timestamp_of_pagechange);
2108 } else {
2109 $other = User::newFromName( $shortTitle );
2110 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2111 // An anonymous user
2112 $other = new User();
2113 $other->setName( $shortTitle );
2114 }
2115 if( $other ) {
2116 $other->setNewtalk(1);
2117 $other->saveNewtalk();
2118 }
2119 }
2120 }
2121
2122 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2123 $wgMessageCache->replace( $shortTitle, $text );
2124 }
2125 }
2126 }
2127
2128 /**
2129 * @todo document this function
2130 * @private
2131 * @param string $oldid Revision ID of this article revision
2132 */
2133 function setOldSubtitle( $oldid=0 ) {
2134 global $wgLang, $wgOut, $wgUser;
2135
2136 $current = ( $oldid == $this->mLatest );
2137 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2138 $sk = $wgUser->getSkin();
2139 $lnk = $current
2140 ? wfMsg( 'currentrevisionlink' )
2141 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2142 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2143 $nextlink = $current
2144 ? wfMsg( 'nextrevision' )
2145 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2146 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2147 $wgOut->setSubtitle( $r );
2148 }
2149
2150 /**
2151 * This function is called right before saving the wikitext,
2152 * so we can do things like signatures and links-in-context.
2153 *
2154 * @param string $text
2155 */
2156 function preSaveTransform( $text ) {
2157 global $wgParser, $wgUser;
2158 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2159 }
2160
2161 /* Caching functions */
2162
2163 /**
2164 * checkLastModified returns true if it has taken care of all
2165 * output to the client that is necessary for this request.
2166 * (that is, it has sent a cached version of the page)
2167 */
2168 function tryFileCache() {
2169 static $called = false;
2170 if( $called ) {
2171 wfDebug( " tryFileCache() -- called twice!?\n" );
2172 return;
2173 }
2174 $called = true;
2175 if($this->isFileCacheable()) {
2176 $touched = $this->mTouched;
2177 $cache = new CacheManager( $this->mTitle );
2178 if($cache->isFileCacheGood( $touched )) {
2179 global $wgOut;
2180 wfDebug( " tryFileCache() - about to load\n" );
2181 $cache->loadFromFileCache();
2182 return true;
2183 } else {
2184 wfDebug( " tryFileCache() - starting buffer\n" );
2185 ob_start( array(&$cache, 'saveToFileCache' ) );
2186 }
2187 } else {
2188 wfDebug( " tryFileCache() - not cacheable\n" );
2189 }
2190 }
2191
2192 /**
2193 * Check if the page can be cached
2194 * @return bool
2195 */
2196 function isFileCacheable() {
2197 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2198 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2199
2200 return $wgUseFileCache
2201 and (!$wgShowIPinHeader)
2202 and ($this->getID() != 0)
2203 and ($wgUser->isAnon())
2204 and (!$wgUser->getNewtalk())
2205 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2206 and (empty( $action ) || $action == 'view')
2207 and (!isset($oldid))
2208 and (!isset($diff))
2209 and (!isset($redirect))
2210 and (!isset($printable))
2211 and (!$this->mRedirectedFrom);
2212 }
2213
2214 /**
2215 * Loads cur_touched and returns a value indicating if it should be used
2216 *
2217 */
2218 function checkTouched() {
2219 $fname = 'Article::checkTouched';
2220 if( !$this->mDataLoaded ) {
2221 $dbr =& $this->getDB();
2222 $data = $this->pageDataFromId( $dbr, $this->getId() );
2223 if( $data ) {
2224 $this->loadPageData( $data );
2225 }
2226 }
2227 return !$this->mIsRedirect;
2228 }
2229
2230 /**
2231 * Edit an article without doing all that other stuff
2232 * The article must already exist; link tables etc
2233 * are not updated, caches are not flushed.
2234 *
2235 * @param string $text text submitted
2236 * @param string $comment comment submitted
2237 * @param bool $minor whereas it's a minor modification
2238 */
2239 function quickEdit( $text, $comment = '', $minor = 0 ) {
2240 $fname = 'Article::quickEdit';
2241 wfProfileIn( $fname );
2242
2243 $dbw =& wfGetDB( DB_MASTER );
2244 $dbw->begin();
2245 $revision = new Revision( array(
2246 'page' => $this->getId(),
2247 'text' => $text,
2248 'comment' => $comment,
2249 'minor_edit' => $minor ? 1 : 0,
2250 ) );
2251 $revisionId = $revision->insertOn( $dbw );
2252 $this->updateRevisionOn( $dbw, $revision );
2253 $dbw->commit();
2254
2255 wfProfileOut( $fname );
2256 }
2257
2258 /**
2259 * Used to increment the view counter
2260 *
2261 * @static
2262 * @param integer $id article id
2263 */
2264 function incViewCount( $id ) {
2265 $id = intval( $id );
2266 global $wgHitcounterUpdateFreq;
2267
2268 $dbw =& wfGetDB( DB_MASTER );
2269 $pageTable = $dbw->tableName( 'page' );
2270 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2271 $acchitsTable = $dbw->tableName( 'acchits' );
2272
2273 if( $wgHitcounterUpdateFreq <= 1 ){ //
2274 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2275 return;
2276 }
2277
2278 # Not important enough to warrant an error page in case of failure
2279 $oldignore = $dbw->ignoreErrors( true );
2280
2281 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2282
2283 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2284 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2285 # Most of the time (or on SQL errors), skip row count check
2286 $dbw->ignoreErrors( $oldignore );
2287 return;
2288 }
2289
2290 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2291 $row = $dbw->fetchObject( $res );
2292 $rown = intval( $row->n );
2293 if( $rown >= $wgHitcounterUpdateFreq ){
2294 wfProfileIn( 'Article::incViewCount-collect' );
2295 $old_user_abort = ignore_user_abort( true );
2296
2297 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2298 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2299 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2300 'GROUP BY hc_id');
2301 $dbw->query("DELETE FROM $hitcounterTable");
2302 $dbw->query('UNLOCK TABLES');
2303 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2304 'WHERE page_id = hc_id');
2305 $dbw->query("DROP TABLE $acchitsTable");
2306
2307 ignore_user_abort( $old_user_abort );
2308 wfProfileOut( 'Article::incViewCount-collect' );
2309 }
2310 $dbw->ignoreErrors( $oldignore );
2311 }
2312
2313 /**#@+
2314 * The onArticle*() functions are supposed to be a kind of hooks
2315 * which should be called whenever any of the specified actions
2316 * are done.
2317 *
2318 * This is a good place to put code to clear caches, for instance.
2319 *
2320 * This is called on page move and undelete, as well as edit
2321 * @static
2322 * @param $title_obj a title object
2323 */
2324
2325 function onArticleCreate($title_obj) {
2326 global $wgUseSquid, $wgPostCommitUpdateList;
2327
2328 $title_obj->touchLinks();
2329 $titles = $title_obj->getLinksTo();
2330
2331 # Purge squid
2332 if ( $wgUseSquid ) {
2333 $urls = $title_obj->getSquidURLs();
2334 foreach ( $titles as $linkTitle ) {
2335 $urls[] = $linkTitle->getInternalURL();
2336 }
2337 $u = new SquidUpdate( $urls );
2338 array_push( $wgPostCommitUpdateList, $u );
2339 }
2340 }
2341
2342 function onArticleDelete($title_obj) {
2343 $title_obj->touchLinks();
2344 }
2345
2346 function onArticleEdit($title_obj) {
2347 // This would be an appropriate place to purge caches.
2348 // Why's this not in here now?
2349 }
2350
2351 /**#@-*/
2352
2353 /**
2354 * Info about this page
2355 * Called for ?action=info when $wgAllowPageInfo is on.
2356 *
2357 * @access public
2358 */
2359 function info() {
2360 global $wgLang, $wgOut, $wgAllowPageInfo;
2361 $fname = 'Article::info';
2362
2363 if ( !$wgAllowPageInfo ) {
2364 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2365 return;
2366 }
2367
2368 $page = $this->mTitle->getSubjectPage();
2369
2370 $wgOut->setPagetitle( $page->getPrefixedText() );
2371 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2372
2373 # first, see if the page exists at all.
2374 $exists = $page->getArticleId() != 0;
2375 if( !$exists ) {
2376 $wgOut->addHTML( wfMsg('noarticletext') );
2377 } else {
2378 $dbr =& $this->getDB( DB_SLAVE );
2379 $wl_clause = array(
2380 'wl_title' => $page->getDBkey(),
2381 'wl_namespace' => $page->getNamespace() );
2382 $numwatchers = $dbr->selectField(
2383 'watchlist',
2384 'COUNT(*)',
2385 $wl_clause,
2386 $fname,
2387 $this->getSelectOptions() );
2388
2389 $pageInfo = $this->pageCountInfo( $page );
2390 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2391
2392 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2393 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2394 if( $talkInfo ) {
2395 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2396 }
2397 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2398 if( $talkInfo ) {
2399 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2400 }
2401 $wgOut->addHTML( '</ul>' );
2402
2403 }
2404 }
2405
2406 /**
2407 * Return the total number of edits and number of unique editors
2408 * on a given page. If page does not exist, returns false.
2409 *
2410 * @param Title $title
2411 * @return array
2412 * @access private
2413 */
2414 function pageCountInfo( $title ) {
2415 $id = $title->getArticleId();
2416 if( $id == 0 ) {
2417 return false;
2418 }
2419
2420 $dbr =& $this->getDB( DB_SLAVE );
2421
2422 $rev_clause = array( 'rev_page' => $id );
2423 $fname = 'Article::pageCountInfo';
2424
2425 $edits = $dbr->selectField(
2426 'revision',
2427 'COUNT(rev_page)',
2428 $rev_clause,
2429 $fname,
2430 $this->getSelectOptions() );
2431
2432 $authors = $dbr->selectField(
2433 'revision',
2434 'COUNT(DISTINCT rev_user_text)',
2435 $rev_clause,
2436 $fname,
2437 $this->getSelectOptions() );
2438
2439 return array( 'edits' => $edits, 'authors' => $authors );
2440 }
2441
2442 /**
2443 * Return a list of templates used by this article.
2444 * Uses the links table to find the templates
2445 *
2446 * @return array
2447 */
2448 function getUsedTemplates() {
2449 $result = array();
2450 $id = $this->mTitle->getArticleID();
2451
2452 $db =& wfGetDB( DB_SLAVE );
2453 $res = $db->select( array( 'pagelinks' ),
2454 array( 'pl_title' ),
2455 array(
2456 'pl_from' => $id,
2457 'pl_namespace' => NS_TEMPLATE ),
2458 'Article:getUsedTemplates' );
2459 if ( false !== $res ) {
2460 if ( $db->numRows( $res ) ) {
2461 while ( $row = $db->fetchObject( $res ) ) {
2462 $result[] = $row->pl_title;
2463 }
2464 }
2465 }
2466 $db->freeResult( $res );
2467 return $result;
2468 }
2469 }
2470
2471 ?>